// src/pages/Device/List.tsx
import { useState } from 'react'
import { Table, Input, Select, Space } from 'antd'
import { useQuery, keepPreviousData  } from '@tanstack/react-query'
import { getDevicePage } from '@/api/device'
import type { DeviceListReq } from '@/api/device'

export default function DeviceList() {
  const [params, setParams] = useState<DeviceListReq>({ pageNum: 1, pageSize: 10 })
  const { data: resp, isFetching } = useQuery({queryKey: ['devicePage', params], queryFn: () => getDevicePage(params), 
    placeholderData: keepPreviousData, // 保持旧数据，不闪屏
  })
  const data = resp?.data

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 80 },
    { title: '设备名称', dataIndex: 'name' },
    { title: '类型', dataIndex: 'type', render: (v: string) => v.toUpperCase() },
    { title: '状态', dataIndex: 'status', render: (v: 0 | 1) => (v ? '在线' : '离线') },
    { title: '创建时间', dataIndex: 'createdAt' },
  ]

  return (
    <>
      <Space style={{ marginBottom: 16 }}>
        <Input.Search
          placeholder="按名称搜索"
          onSearch={(name) => setParams({ ...params, name, pageNum: 1 })}
          allowClear
        />
        <Select
          placeholder="全部类型"
          allowClear
          options={[
            { label: '摄像头', value: 'camera' },
            { label: '传感器', value: 'sensor' },
            { label: '网关',   value: 'gateway' },
          ]}
          onChange={(type) => setParams({ ...params, type, pageNum: 1 })}
        />
      </Space>

      <Table
        rowKey="id"
        loading={isFetching}
        dataSource={data?.list}
        columns={columns}
        pagination={{
          current: params.pageNum,
          pageSize: params.pageSize,
          total: data?.total,
          showSizeChanger: true,
          onChange: (pageNum, pageSize) =>
            setParams({ ...params, pageNum, pageSize }),
        }}
      />
    </>
  )
}